//
//  ConfigurationTableViewController.m
//  Moko
//
//  Created by cj848 on 11. 7. 24..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ConfigurationTableViewController.h"
#import "MokoAppDelegate.h"
#import "SwitchTableCell.h"
@implementation ConfigurationTableViewController
@synthesize dbPath;
@synthesize totalBytesOfDataUsage,total3GBytesOfDataUsage,totalWifiBytesOfDataUsage;
-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if( self ) {
        self.title = @"설정/정보";
        sectionTitles = [[NSArray alloc] initWithObjects:@"설정", @"어플 구동 후 데이터 사용량\n(로드된 이미지와 외부 링크 클릭시 사용량은 포함되지 않습니다.)", @"제작자 정보", @"개발자 도와주기(큰 힘이 됩니다.)", nil];
        rowDataSource = [[NSMutableDictionary alloc] init];
        for( int i = 0, l = [sectionTitles count]; i < l; i++ ) {
            [rowDataSource setValue:[[NSMutableArray new] autorelease] forKey:[sectionTitles objectAtIndex:i]];
        }
        GET_APPDELEGATE;
        NSMutableArray* configArr = [rowDataSource objectForKey:[sectionTitles objectAtIndex:0]];
        [configArr addObject:@"자동 로그인"];
        [configArr addObject:@"공지 게시글 보기"];
        [configArr addObject:@"댓글 낙인 사용(터치설정)"];
        [configArr addObject:@"글쓰기 낙인 사용(터치설정)"];
        [configArr addObject:@"쪽지 알림 기능 사용"];
        [configArr addObject:@"본문 내 이미지 기본 표시"];
        NSMutableArray* dataArr = [rowDataSource objectForKey:[sectionTitles objectAtIndex:1]];
        [dataArr addObject:@"총 사용량 : 약 %.2f MB"];
        [dataArr addObject:@"3G 사용량 : 약 %.2f MB"];
        [dataArr addObject:@"WiFi 사용량 : 약 %.2f MB"];
        
        NSMutableArray* infoArr = [rowDataSource objectForKey:[sectionTitles objectAtIndex:2]];
        [infoArr addObject:[NSString stringWithFormat:@"제작자 이름 : %@", delegate.configVO.developerName]];
        [infoArr addObject:[NSString stringWithFormat:@"버전 : %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
        [infoArr addObject:[NSString stringWithFormat:@"문의 사항은 %@", delegate.configVO.developerEmail]];
        
        NSMutableArray* helpArr = [rowDataSource objectForKey:[sectionTitles objectAtIndex:3]];
        [helpArr addObject:@"Paypal : 가입후 가능"];
        [helpArr addObject:@"Pbank : 휴대폰 결제만 가능"];
    }
    return self;
}
-(void)switchValueChanged:(id)sender {
    UISwitch* st = sender;
    GET_APPDELEGATE;
    NSNumber* bValue = [NSNumber numberWithBool:st.on];
    switch(st.tag) {
        case 0:
            delegate.configVO.autoLogin = bValue;
            break;
        case 1:
            delegate.configVO.showNotice = bValue;
            break;
        case 2:
            delegate.configVO.useCommentSignature = bValue;
            break;
        case 3:
            delegate.configVO.useWriteSignature = bValue;
            break;
        case 4:
            delegate.configVO.showMemoNoti = bValue;
            break;
        case 5:
            delegate.configVO.showImageInArticle = bValue;
            break;
    }
    NSError* saveError;
    [delegate.managedObjectContext save:&saveError];
}
-(void)backStep {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc
{
    [rowDataSource release];
    [sectionTitles release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithTitle:@"초기화" style:UIBarButtonItemStylePlain target:self action:@selector(setDefault)];
    self.navigationItem.rightBarButtonItem = item;
    [item release];
    
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
        UIImage* image = [UIImage imageNamed:@"back_left_button.png"];
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:image forState:UIControlStateNormal];
        [button addTarget:self action:@selector(backStep) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, 0, image.size.width/2, image.size.height/2);
        item = [[UIBarButtonItem alloc] initWithCustomView:button];
        self.navigationItem.hidesBackButton = YES;
        self.navigationItem.leftBarButtonItem = item;
        [item release];
    }
}
- (void)setDefault {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"설정 초기화" message:@"설정을 모두 초기화 하시겠습니까?" delegate:self cancelButtonTitle:@"취소" otherButtonTitles:@"확인", nil];
    alert.tag = 1000;
    [alert show];
    [alert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    GET_APPDELEGATE;
    if( alertView.tag == 1000 && buttonIndex == 1 ) {
        [delegate setDefaultConfig];
        [self.tableView reloadData];
    }
    else if( alertView.tag == 1001 && buttonIndex == 1 ) {
        for( UIView* view in [alertView subviews] ) {
            if( [view isKindOfClass:[UITextField class]] == YES ) {
                delegate.configVO.commentSignature = ((UITextField*)view).text;
                NSError* error;
                if( [delegate.managedObjectContext save:&error] == YES )
                    [self.tableView reloadData];
                else
                    NSLog(@"Save Failed");
            }
        }
    }
    else if( alertView.tag == 1002 && buttonIndex == 1 ) {
        for( UIView* view in [alertView subviews] ) {
            if( [view isKindOfClass:[UITextView class]] == YES ) {
                delegate.configVO.writeSignature = ((UITextView*)view).text;
                NSError* error;
                if( [delegate.managedObjectContext save:&error] == YES )
                    [self.tableView reloadData];
                else
                    NSLog(@"Save Failed");
            }
        }
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [sectionTitles count];
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [sectionTitles objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int count = [[rowDataSource objectForKey:[sectionTitles objectAtIndex:section]] count];
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    static NSString* switchCellIdentifier = @"switch";
    
    UITableViewCell *cell = nil;
    if( indexPath.section != 0 ) {
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:13.0];
        }
    }
    else {
        cell = [tableView dequeueReusableCellWithIdentifier:switchCellIdentifier];
        if (cell == nil) {
            cell = [[[SwitchTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:switchCellIdentifier] autorelease];
            [((SwitchTableCell*)cell).switchObj addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
            cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:13.0];
        }
    }
    
    NSString* text = [[rowDataSource objectForKey:[sectionTitles objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    // 설정
    if( indexPath.section == 0 ) {
        GET_APPDELEGATE;
        cell.textLabel.text = [[rowDataSource objectForKey:[sectionTitles objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
        ((SwitchTableCell*)cell).switchObj.tag = indexPath.row;
        switch( indexPath.row ) {
            case 0:
                ((SwitchTableCell*)cell).switchObj.on = [delegate.configVO.autoLogin boolValue];
                break;
            case 1:
                ((SwitchTableCell*)cell).switchObj.on = [delegate.configVO.showNotice boolValue];
                break;
            case 2:
                ((SwitchTableCell*)cell).switchObj.on = [delegate.configVO.useCommentSignature boolValue];
                break;
            case 3:
                ((SwitchTableCell*)cell).switchObj.on = [delegate.configVO.useWriteSignature boolValue]; 
                break;
            case 4:
                ((SwitchTableCell*)cell).switchObj.on = [delegate.configVO.showMemoNoti boolValue]; 
                break;
            case 5:
                ((SwitchTableCell*)cell).switchObj.on = [delegate.configVO.showImageInArticle boolValue]; 
                break;
        }
    }
    // 그 외 정보
    else if( indexPath.section == 1 ) {
        // 메가 단위로 표현
        float one_megabyte = 1048576.0f;
        switch( indexPath.row ) {
            case 0:
                cell.textLabel.text = [NSString stringWithFormat:text, totalBytesOfDataUsage / one_megabyte];
                break;
            case 1:
                cell.textLabel.text = [NSString stringWithFormat:text, total3GBytesOfDataUsage / one_megabyte];
                break;
            case 2:
                cell.textLabel.text = [NSString stringWithFormat:text, totalWifiBytesOfDataUsage / one_megabyte];
                break;
        }
    }
    else cell.textLabel.text = text;
    
    // Configure the cell...
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( indexPath.section == 0 ) {
        if( indexPath.row == 2 ) {
            UIAlertView* dialog = [[[UIAlertView alloc] init] retain];
            [dialog setDelegate:self];
            [dialog setTitle:@"댓글 낙인 설정"];
            [dialog setMessage:@" "];
            [dialog addButtonWithTitle:@"취소"];
            [dialog addButtonWithTitle:@"확인"];
            dialog.cancelButtonIndex = 0;
            dialog.tag = 1001;
            GET_APPDELEGATE;
            UITextField *nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
            [nameField setBackgroundColor:[UIColor whiteColor]];
            nameField.text = delegate.configVO.commentSignature;
            [dialog addSubview:nameField];
//            CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 45.0);
//            [dialog setTransform: moveUp];
            [dialog show];
            [dialog release];
            [nameField release];
        }
        else if( indexPath.row == 3 ) {
            UIAlertView* dialog = [[[UIAlertView alloc] init] retain];
            [dialog setDelegate:self];
            [dialog setTitle:@"글쓰기 낙인 설정"];
            [dialog setMessage:@"\n\n\n\n\n"];
            [dialog addButtonWithTitle:@"취소"];
            [dialog addButtonWithTitle:@"확인"];
            dialog.cancelButtonIndex = 0;
            dialog.tag = 1002;
            GET_APPDELEGATE;
            UITextView *nameField = [[UITextView alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 100.0)];
            [nameField setBackgroundColor:[UIColor whiteColor]];
            nameField.text = delegate.configVO.writeSignature;
            [dialog addSubview:nameField];
            //            CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 45.0);
            //            [dialog setTransform: moveUp];
            [dialog show];
            [dialog release];
            [nameField release];
        }
    }
    else if(indexPath.section == 3 ) {
        if( indexPath.row == 0 ) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=cj848%40hanmail%2enet&lc=KR&item_name=Moko%20Donation&item_number=mokodonation&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted"]];
        }
        else if( indexPath.row == 1 ) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.pbank.co.kr/svc/guest_remit/pop_remit_main.jsp?fix=55301&b_bankbook=213918864&fbid="]];
        }
    }
}

@end
